package com.gxa.common.util;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 分页工具类
 */
public class PageUtils implements Serializable {
	private static final long serialVersionUID = 1L;
	private String paramHref;

	public boolean pageInit(Page page, HttpServletRequest request){
//		if (page.getTotalCount() > page.getPageSize() && page.getCurrPage() != 0){
		if (page.getTotalCount() > page.getPageSize()){
			String servletPath = request.getServletPath();
			// 获取分页参数地址
			StringBuffer param = new StringBuffer(servletPath + "?");
			Enumeration em = request.getParameterNames();
			while (em.hasMoreElements()) {
				String name = (String) em.nextElement();
				if(!"page".equals(name)){
					String value = request.getParameter(name);
					param.append(name + "=" + value + "&");
				}
			}
			this.paramHref = param.toString();
			return true;
		}
		return false;
	}

	public List<String> pageCode(Page page){
		int number = page.getCurrPage()+1;
		int totalPages = page.getTotalPage();
		int start = 0;
		int length = 7;
		int half = length % 2 == 0 ? length / 2 : length / 2 + 1;
		List<String> codeList = new ArrayList<>();

		if(totalPages > length && number > half){
			start = number - half;
		}
		if(totalPages > length && number > totalPages - half){
			start = totalPages - length;
		}
		for (int i=1; i <= (totalPages > length ? length : totalPages); i++){
			codeList.add(String.valueOf( i + start));
		}
		if(totalPages > length && number > half){
			codeList.set(0, "1");
			codeList.set(1, "…");
		}
		if(totalPages > length && number < totalPages - (half-1)){
			codeList.set(length-2, "…");
			codeList.set(length-1, String.valueOf(totalPages));
		}
		return codeList;
	}

	public String pageActive(Page page, String pageCode, String className){
		int number = page.getCurrPage();
		if(!"…".equals(pageCode)){
			if(number == Integer.valueOf(pageCode) - 1){
				return " "+className;
			}
		}
		return "";
	}

	public boolean isPrevious(Page page){
		return page.getCurrPage() != 0;
	}

	public boolean isNext(Page page){
		return page.getCurrPage() != page.getTotalPage() - 1;
	}

	public boolean isCode(String pageCode){
		return "…".equals(pageCode);
	}

	public String pageHref(String pageCode){
		return paramHref + "page=" + pageCode;
	}

}
